package dao

import (
	"bilibi.com/comment/library/cache/redis"
	"context"
	gredis "github.com/go-redis/redis"

	"bilibi.com/comment/conf"
	"bilibi.com/comment/library/database/orm"

	"github.com/jinzhu/gorm"
)

// Dao dao
type Dao struct {
	c     *conf.Config
	db    *gorm.DB
	redis *gredis.Client
}

// New init mysql db
func New(c *conf.Config) (d *Dao) {
	d = &Dao{
		c:     c,
		db:    orm.NewMySQL(c.ORM),
		redis: redis.NewRedis(c.REDIS),
	}
	d.initORM()
	return
}

func (d *Dao) initORM() {
	d.db.LogMode(true)
}

// Close close the resource.
func (d *Dao) Close() {
	if d.db != nil {
		d.db.Close()
	}
	if d.redis != nil {
		d.redis.Close()
	}
}

// Ping dao ping
func (d *Dao) Ping(c context.Context) (err error) {
	if d.db != nil {
		err = d.db.DB().PingContext(c)
		if err != nil {
			return
		}
	}
	if d.redis != nil {
		err = d.redis.Ping().Err()
		if err != nil {
			return
		}
	}
	return
}
